package com.weibei.common.utils.file;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.HeaderResponse;
import com.obs.services.model.PutObjectResult;
import com.weibei.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

@Component
public class HuaWeiCloudUtil {
    //    @Value("${storage.huaweicloud.endpoint}")
    private String endPoint = "obs.cn-east-2.myhuaweicloud.com";
    //    @Value("${storage.huaweicloud.accessKey}")
    private String ak = "L5NOVKDWCOI3YBQ1X3Q1";
    //    @Value("${storage.huaweicloud.secretKey}")
    private String sk = "QOKn94MTGpnMukJYb0jUT4MOhL1GQFYaWOFDsJ34";

    private String hwRetUrl1 = "https://hongtai-public.obs.cn-east-2.myhuaweicloud.com:443/";
    private String hwRetUrl2 = "https://hongtai-public.obs.cn-east-2.myhuaweicloud.com/";
    private String myUrl = "https://e-mallfile.dfpv.com.cn/";


    public String storage(InputStream inputStream, String name) {
        // 工程中可以只保留一个全局的ObsClient实例
        // ObsClient是线程安全的，可在并发场景下使用
        ObsClient obsClient = null;
        String objectUrl = "";
        try {
            // 创建ObsClient实例
            obsClient = new ObsClient(ak, sk, endPoint);
            // 调用接口进行操作，例如上传对象
            HeaderResponse response = obsClient.putObject("hongtai-public", name, inputStream);
            objectUrl = ((PutObjectResult) response).getObjectUrl();
            //替换成自己的url
            if (StringUtils.isNotEmpty(objectUrl)){
                objectUrl = objectUrl.replace(hwRetUrl1,myUrl).replace(hwRetUrl2,myUrl);
            }
        } catch (ObsException e) {
            e.printStackTrace();
        } finally {
            // 关闭ObsClient实例，如果是全局ObsClient实例，可以不在每个方法调用完成后关闭
            // ObsClient在调用ObsClient.close方法关闭后不能再次使用
            if (obsClient != null) {
                try {
                     obsClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return objectUrl;
    }
}
